package com.google.code.sfa.nextgen;

import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import com.google.code.sfa.parse.Trace;
import org.biojava.bio.seq.DNATools;
import org.biojava.bio.symbol.Symbol;

public class NextGenIndex {

    private Symbol _a, _t, _c, _g; //0,1,2,3
    private int[] _mask;
    private int _maskPos;
    private Map<Integer,List<Trace>> _index;

    private Trace _currentTrace;
    private int _current;
    private List<Trace> _matches;

    public NextGenIndex( int[] mask) {
	_a = DNATools.a();
	_t = DNATools.t();
	_c = DNATools.c();
	_g = DNATools.g();
	
	this._mask = mask;
	this._maskPos = 0;
	this._index = new HashMap<Integer, List<Trace>>();
    }

    public void reset(Trace t) {
	this._maskPos = 0;
	this._current = 0;
	_currentTrace = t;
	_matches = null;
    }

    public void add( Symbol s) {
	
	if( _maskPos >= _mask.length) {
	    return;
	}
	if( _mask[_maskPos] == 1 ) {

	    _current = _current << 2;

	    if( s == _a) {
		_current |= 0;
	    } else if( s == _t) {
		_current |= 1;
	    } else if( s == _c) {
		_current |= 2;
	    } else if( s == _g) {
		_current |= 3;
	    }
	}
	_maskPos++;
	if( _maskPos >= _mask.length ) {
	    if( _index.containsKey( _current) ) {
		_matches = _index.get( _current);
		if( _currentTrace != null) {
		    if( !_matches.contains( _currentTrace)) {
			_matches.add( _currentTrace);
		    }
		}
	    } else {
		_matches = new ArrayList<Trace>();
		if( _currentTrace != null) {
		    _index.put( _current, _matches);
		    _matches.add( _currentTrace);
		}
	    }
	}
    }


    public List<Trace> getMatches() {
	return _matches;
    }


}

